#!/usr/bin/env python

from sys import argv, exit
from fgs.client.Client import Client

user = "Dave"
passwd = "lapin"

if len(argv) == 2:
    portal_uri = argv[1]
    if not portal_uri.endswith("backend.php"):
        portal_uri += "backend.php"
    elif not portal_uri.endswith("/backend.php"):
        portal_uri += "/backend.php"
else:
    portal_uri = None

c = Client(portal_uri, user, passwd)

if not c.portal:
    print "Retrieving portals..."
    pl = c.portals
    print "Portal list:"
    for p in pl:
        print " ", p[0]

    choice = int(raw_input("Select portal: "))-1
    print pl[choice][1]
    c.get_portal(pl[choice][1], user, passwd)

    print "Welcome to the %s portal!" % pl[choice][0]
else:
    print "Welcome to the portal!"

games = c.portal.games
print "Available games:"
for g in games:
    print " ", g.name, "(%s)" % g.desc
choice = int(raw_input("Select game: "))-1

print "Playing %s" % games[choice].name

servers = games[choice].servers
print "Available servers:"
for s in servers:
    print s.name, "(%s), running version %s" % (s.host, s.version)

choice = int(raw_input("Select server: "))-1

print "Selected server %s" % servers[choice].host
print "Initializing bridge and authenticating..."

b = servers[choice].make_bridge()

print "Bridge initialized, now please start the game and point it to localhost!"
try:
    while True:
        from time import sleep
        sleep(100)
except KeyboardInterrupt:
    print "Interrupt caught, exiting."
    b.shutdown_bridge()

#portal = ServerProxy(portal_uri)

#print "Connecting to FGS portal %s" % portal_uri

#user = raw_input("Login: ")
#passwd = raw_input("Password (echo is ON): ")

#try:
#    sid = portal.user.login(user, passwd)
#except Fault:
#    print "Login failed"
#    exit(1)

#game_list = portal.user.getgamelist()
#print "Games found:"
#for game in game_list:
#    print "  - %s, start on port %s (%s)" % (game['game_name'], game['port'], game['game_desc'])
#    server_list = portal.user.getserverlist(game['game_id'])
#    if len(server_list) == 0:
#        print "     **(No servers available)**"
#    for server in server_list:
#        if server['host'] == "127.0.0.1":
#            server['host'] = "192.168.1.3"
#        print "     * Available on %s:%s (FGSS %s), game version %s" % (server['host'], server['port'], server['fgs'], server['game_version'])

# Select server
# Connect w/ socket to FGSS
# Auth to FGSS
# Open server socket
# Bridge server socket w/ FGSS socket
